#include <bits/stdc++.h>

using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {

        ListNode *fast = head;
        ListNode *slow = head;
        ListNode *pre = nullptr;
        while (n--)
        {
            fast = fast->next;
            if (fast == nullptr && n != 0)
            {
                return nullptr;
            }
        }
        while (fast)
        {
            pre = slow;
            fast = fast->next;
            slow = slow->next;
        }

        if (slow != head)
        {
            pre->next = slow->next;
        }
        else
        {
            pre = slow->next;
            return pre;
        }
        return head;
    }
};